package com.example.springbootdemo.service.impl;

import com.example.springbootdemo.dao.UserRepository;
import com.example.springbootdemo.dto.User;
import com.example.springbootdemo.entity.Tuser;
import com.example.springbootdemo.service.UserServiceI;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserServiceI {
    @Resource
    UserRepository userDao;
    @Override
    public User getUserById(int id) {
        Tuser tuser=userDao.getById(id);
        return e2d(tuser);
    }

    @Override
    public List<User> allUsers() {
        List<Tuser> tusers=userDao.findAll();
        return e2d(tusers);
    }

    @Override
    public User addUser(User user) {
        Tuser tuser=new Tuser();
        BeanUtils.copyProperties(user,tuser,new String[]{"id"});
        userDao.save(tuser);
        BeanUtils.copyProperties(tuser,user);
        return user;
    }

    private User e2d(Tuser tuser){
        if(tuser==null)
            return null;
        User user=new User();
        BeanUtils.copyProperties(tuser,user);
        return user;

    }
    private List<User> e2d(List<Tuser> tusers){
        List<User> users=new ArrayList<>();
        if(tusers!=null&&tusers.size()>0) {
            for (Tuser u : tusers) {
                users.add(e2d(u));
            }
        }
        return users;
    }
}
